package atomgit_hook

import (
	"time"

	"atomgit.com/openlinksaas-org/proto-gen-go.git/events/events_atomgit"
)

type Commit struct {
	Added     []string `json:"added"`
	Author    GitUser  `json:"author"`
	Committer GitUser  `json:"committer"`
	Distinct  bool     `json:"distinct"`
	Id        string   `json:"id"`
	Message   string   `json:"message"`
	Modified  []string `json:"modified"`
	Removed   []string `json:"removed"`
	Timestamp string   `json:"timestamp"`
	TreeId    string   `json:"tree_id"`
	Url       string   `json:"url"`
}

func (item *Commit) ToProtoBuf() *events_atomgit.Commit {
	ts := int64(0)
	t, err := time.Parse(time.RFC3339, item.Timestamp)
	if err == nil {
		ts = t.UnixNano() / 1e6
	}
	return &events_atomgit.Commit{
		Added:     item.Added,
		Author:    item.Author.ToProtoBuf(),
		Committer: item.Committer.ToProtoBuf(),
		Distinct:  item.Distinct,
		Id:        item.Id,
		Message:   item.Message,
		Modified:  item.Modified,
		Removed:   item.Removed,
		Timestamp: ts,
		TreeId:    item.TreeId,
		Url:       item.Url,
	}
}

type PushHook struct {
	After      string     `json:"after"`
	Before     string     `json:"before"`
	Commits    []Commit   `json:"commits"`
	Compare    string     `json:"compare"`
	Created    bool       `json:"created"`
	Deleted    bool       `json:"deleted"`
	Forced     bool       `json:"forced"`
	HeadCommit Commit     `json:"head_commit"`
	Ref        string     `json:"ref"`
	Repository Repository `json:"repository"`
	Sender     User       `json:"sender"`
}

func (item *PushHook) ToProtoBuf() *events_atomgit.PushEvent {
	commits := []*events_atomgit.Commit{}
	for _, commit := range item.Commits {
		commits = append(commits, commit.ToProtoBuf())
	}
	return &events_atomgit.PushEvent{
		After:      item.After,
		Before:     item.Before,
		Commits:    commits,
		Compare:    item.Compare,
		Created:    item.Created,
		Deleted:    item.Deleted,
		Forced:     item.Forced,
		HeadCommit: item.HeadCommit.ToProtoBuf(),
		Ref:        item.Ref,
		Repository: item.Repository.ToProtoBuf(),
		Sender:     item.Sender.ToProtoBuf(),
	}
}
